<template>
  <!-- 弹框-->
  <a-modal
    title="个税凭证"
    :visible="oveVisibles"
    @cancel="clickCancel()"
    @ok="clickConfirm()"
    width="50%"
    :confirmLoading="confirmLoading"
  >
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      labelAlign="left"
    >
      <a-form-model-item label="个税申报" prop="personalApply" style="width: 90%;">
        <a-radio-group v-model="needApply" >
          <a-radio :value="1">
            需要办理
          </a-radio>
          <a-radio :value="0">
            无需办理
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="needApply == 1" label="申报金额" prop="personalTax" style="width: 90%;">
        <a-input
          v-model="form.personalTax"
          placeholder="请输入申报金额"
          :min="0.01"
          :precision="2"
          @input="(e) => (this.form.personalTax = moneyCheck(e.target.value))"
          style="width: 90%;"/>
      </a-form-model-item>
      <a-form-model-item v-if="needApply == 1" label="申报日期" prop="approveDate" style="width: 90%;">
        <a-date-picker v-model="form.approveDate" placeholder="年-月-日" :format="dateFormat" :valueFormat="dateFormat" style="width: 90%;" />
      </a-form-model-item>
      <a-form-model-item v-if="needApply == 1" label="上传凭证" prop="taxUrl" style="width: 90%;">
        <div class="clearfix">
          <span>凭证仅可上传一张，支持格式：PNG/JPG</span>
          <a-upload
            action="/api/common/upload"
            list-type="picture-card"
            :file-list="fileList"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-model-item>
      <a-form-model-item v-if="needApply == 1" label="备注" style="width: 90%;">
        <a-input
          type="textarea"
          v-model="form.taxRemark"
          placeholder="请写明哪些需要缴个税及金额"
          style="width: 90%;"/>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>
<script>
import clonedeep from 'lodash.clonedeep'
// import moment from 'moment'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  props: {
    oveVisibles: {
      default: false,
      type: Boolean
    },
    auditStatus: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      confirmLoading: false,
      dateFormat: 'YYYY-MM-DD', // 时间选择器格式
      rules: {
        // 校验规则
        personalTax: [{ required: true, validator: this.moneyValidate, trigger: 'blur' }],
        approveDate: [{ required: true, message: '请选择申报日期' }],
        taxUrl: [{ required: true, message: '请上传凭证', trigger: 'blur' }],
        needApply: [{ required: true, message: '请选择个税申报', trigger: 'blur' }]
      },
      needApply: 1,
      form: {
        personalTax: '',
        taxRemark: '',
        approveDate: '',
        taxUrl: ''
      },
      condition: false,
      previewVisible: false,
      previewImage: '',
      fileList: [],
      stopUpload: false
    }
  },
  mounted () {},
  watch: {
    auditStatus (newValue) {
      this.form.personalTax = clonedeep(newValue.personalTax) || ''
    },
    oveVisibles (e) {
      !e && setTimeout(() => {
          this.$refs.ruleForm.resetFields()
          this.fileList = []
        }, 500)
    }
  },
  methods: {
    moneyValidate (rule, value, callback) {
      if (!value || +value <= 0 || +value > this.auditStatus.totalAmount) {
        callback(new Error(`申报金额需大于0且小于${this.auditStatus.totalAmount}`)) // eslint-disable-line
        return
      }
      callback()
    },
    // 校验图片格式是否符合要求
    beforeUpload (file) {
      const typeVal = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
      if (!typeVal) {
        this.$message.error('图片格式仅支持“jpg/jpeg/png”')
        this.stopUpload = true
      } else {
        this.stopUpload = false
      }
      return typeVal
    },
    // 校验金额为小数点后两位
    moneyCheck (val) {
      val = val.replace('e', '')
      val = val.replace(/[^0-9.]/g, '')
      val = val.replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3') // 此处还可以限制位数以及大小
      return val
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ file, fileList }) {
      if (this.stopUpload) {
        this.fileList = []
        return
      }
      this.fileList = fileList
      console.log('fileList', file, fileList)
      if (file.status === 'done') {
        if (file.response && file.response.data) {
          this.form.taxUrl = file.response.data
          console.log('success', this.fileList)
          if (this.fileList.length > 1) {
            this.fileList = fileList.slice(-1)
          }
        } else {
          this.fileList = []
          this.$message.error(file.response.detail || '上传失败')
        }
      }
    },
    clickCancel () {
      this.$emit('uploadModalCancel')
    },
    clickConfirm () {
      this.$refs.ruleForm.validate(flag => {
        if (flag) {
          let params = {}
          if (this.needApply === 1) {
            params = {
              id: this.$props.auditStatus.id,
              ...this.form
            }
          } else {
            params = {
              id: this.$props.auditStatus.id,
              personalTax: 0
            }
          }
          this.$emit('roveModalCancel', params)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
